using Auros.Categorisation.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using umbraco;
using umbraco.BasePages;

namespace Auros.Categorisation.Umbraco.Dialogs
{
    /// <summary>
    /// Summary description for moveOrCopy.
    /// </summary>
    public partial class CategoryMoveDialog : UmbracoEnsuredPage
    {
        private int? currentId;
        private Category currentCategory;

        protected override void OnInit(EventArgs e)
        {
            this.currentId = this.GetRequestValue("id");

            if(this.currentId.HasValue)
                this.currentCategory = Categories.GetCategory(this.currentId.Value);

            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            this.JTree.DataBind();

            // Put user code to initialize the page here
            if (!this.IsPostBack)
            {
                this.TreePane.Visible = true;
                this.NoticePane.Visible = true;

                // Caption and properies on BUTTON
                this.OkButton.Text = ui.Text("general", "ok", this.getUser());
                this.OkButton.Attributes.Add("style", "width: 60px");
                this.OkButton.Attributes.Add("disabled", "true");

                this.TreePane.Text = ui.Text("moveOrCopy", "moveTo", this.currentCategory.LocalizedName, base.getUser());
            }

            base.OnLoad(e);
        }

        public void OkButtonClick(object sender, EventArgs e)
        {
            this.HandleCategoryMove();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            
            ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/cmsnode.asmx"));
            ScriptManager.GetCurrent(Page).Services.Add(new ServiceReference("../webservices/legacyAjaxCalls.asmx"));
        }

        private void HandleCategoryMove() 
        {
            int? newParentId = this.GetRequestValue("NewParentId");

            if (newParentId.HasValue && this.currentId.HasValue)
            {
                string oldNodePath = this.GetCategoryTreePath(this.currentId.Value);

                Category newParentCategory = null;

                if (newParentId > 0)
                {
                    newParentCategory = Categories.GetCategory(newParentId.Value);

                    if (newParentCategory.ID != this.currentCategory.ID && !newParentCategory.IsDescendantOf(this.currentCategory))
                    {
                        this.currentCategory.ParentID = newParentId.Value;
                        this.currentCategory.Save();
                    }
                }
                else
                {
                    this.currentCategory.ParentID = 0;
                    this.currentCategory.Save();
                }

                this.Feedback.Text = ui.Text("moveOrCopy", "moveDone", new string[] { this.currentCategory.LocalizedName, newParentCategory == null ? "root" : newParentCategory.LocalizedName }, getUser()) + "</p><p><a href='#' onclick='" + ClientTools.Scripts.CloseModalWindow() + "'>" + ui.Text("closeThisWindow") + "</a>";
                this.Feedback.type = umbraco.uicontrols.Feedback.feedbacktype.success;

                this.TreePane.Visible = false;
                this.NoticePane.Visible = false;
                this.ButtonsPane.Visible = false;

                if (newParentId > 0)
                {
                    this.ClientTools.RefreshTree("categories");
                    //ScriptManager.RegisterStartupScript(this, this.GetType(), "reloadtree", "UmbClientMgr.mainTree().reloadActionNode()", true);
                    //this.ClientTools.SyncTree(oldNodePath, true);
                    this.ClientTools.SyncTree(this.GetCategoryTreePath(this.currentCategory.ID), true);
                }
                else
                    BasePage.Current.ClientTools.ReloadActionNode(true, true);
            }

        }

        /// <summary>
        /// Gets the category tree path.
        /// </summary>
        /// <param name="id">The category id.</param>
        /// <returns>CSV path of the given category.</returns>
        private string GetCategoryTreePath(int id)
        {
            List<int> pathItems = new List<int>(10);

            var categories = new CategoryRepository().GetCategories().ToList();

            Func<int, List<int>> build = null;

            build = (cId) =>
            {
                var a = (from x in categories where x.ID == cId && x.Parent != null && x.Parent.ID > 0 select x.Parent.ID).ToList();

                if (a.Count > 0)
                    a.AddRange(build(a[a.Count - 1]));

                return a;
            };

            pathItems.AddRange(build(id));

            pathItems.Reverse();

            return "root," + string.Join(",", pathItems);
        }

        private int? GetRequestValue(string key)
        {
            int id = -1;

            if (int.TryParse(helper.Request(key), out id))
                return id;
            else
                return null;
        }
    }
}